package com.edee.bigday.member.interceptor;

import com.edee.common.constant.AuthServerConstant;
import com.edee.common.vo.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    //为了线程间共享，使用ThreadLocal：
    public static ThreadLocal<MemberRespVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //  /order/order/status/{orderSn}---->/order/order/status/2340921349808
        //使用Spring的匹配器进行匹配放行路径：
        String requestURI = request.getRequestURI();
        //boolean match = new AntPathMatcher().match("/order/order/status/**", requestURI);
        boolean match = new AntPathMatcher().match("/member/**", requestURI);
        if (match) {
            //如果匹配，直接放行：
            return true;
        }

        MemberRespVo attribute = (MemberRespVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute != null) {
            loginUser.set(attribute);
            return true;
        } else {
            //增加登录提示信息：
            request.getSession().setAttribute("msg", "登录之后，才能正常使用订单服务！");
            //重定向到登录页：
            response.sendRedirect("http://auth.bigday.com/login.html");
            return false;
        }
    }
}
